import Dict from '#models/dict'
import BaseController from '#common/base_controller'
import { deleteIdsValidator } from '#validators/common'
import { createDictValidator, updateDictValidator } from '#validators/dict'
import type { HttpContext } from '@adonisjs/core/http'
import vine from '@vinejs/vine'

export default class DictController extends BaseController {
  async list(ctx: HttpContext) {
    const paramsValidator = vine.compile(
      vine.object({
        className: vine.unionOfTypes([vine.string(), vine.array(vine.string())]),
      })
    )

    const data = await ctx.request.validateUsing(paramsValidator)

    const dict = await Dict.query().whereIn(
      'className',
      vine.helpers.isString(data.className) ? [data.className] : data.className
    )

    return dict
  }

  async create({ request }: HttpContext) {
    const data = await request.validateUsing(createDictValidator)
    return Dict.create(data)
  }

  async detail({ request }: HttpContext) {
    const { id } = request.qs()
    return Dict.findOrFail(id)
  }

  async update({ request }: HttpContext) {
    const id = request.param('id')
    const updateDate = await request.validateUsing(updateDictValidator)
    return Dict.query().where('id', id).update(updateDate)
  }

  async delete({ request }: HttpContext) {
    const ids = await deleteIdsValidator.validate(request.body())
    return Dict.query().whereIn('id', ids).delete()
  }
}
